package com.jumi.microservice.service.admin;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.dto.ExportExcelCommonResponse;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.constant.DelFlag;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.common.page.TableDataInfo;
import com.jumi.microservice.common.utils.DateUtil;
import com.jumi.microservice.common.utils.EnumUtil;
import com.jumi.microservice.config.ExpireTimeConfig;
import com.jumi.microservice.constant.compensation.AfterSaleEnum;
import com.jumi.microservice.constant.compensation.AfterSaleStatusEnum;
import com.jumi.microservice.constant.compensation.CheckStatusEnum;
import com.jumi.microservice.constant.compensation.LockFlagEnum;
import com.jumi.microservice.constant.refundgoods.CancelUserFlagEnum;
import com.jumi.microservice.constant.reissue.*;
import com.jumi.microservice.domain.GoodsSkuMaterialDTO;
import com.jumi.microservice.domain.MaterialSkuRelationshipDTO;
import com.jumi.microservice.dto.order.OrderLogRequest;
import com.jumi.microservice.dto.reissue.*;
import com.jumi.microservice.dto.reponse.UserExternalResponse;
import com.jumi.microservice.dto.serviceDto.*;
import com.jumi.microservice.entity.AfterSealOrder;
import com.jumi.microservice.entity.AfterSealOrderGoods;
import com.jumi.microservice.entity.Compensation;
import com.jumi.microservice.entity.Reissue;
import com.jumi.microservice.enumerate.OrderStatusEnum;
import com.jumi.microservice.exception.RefundGoodsExceptionEnum;
import com.jumi.microservice.exception.ReissueExceptionEnum;
import com.jumi.microservice.mapper.AfterSealOrderGoodsMapper;
import com.jumi.microservice.mapper.AfterSealOrderMapper;
import com.jumi.microservice.mapper.CompensationMapper;
import com.jumi.microservice.mapper.ReissueMapper;
import com.jumi.microservice.material.dto.supplier.JmSupplierResponse;
import com.jumi.microservice.material.service.IJmSupplierService;
import com.jumi.microservice.material.service.IJmWarehouseService;
import com.jumi.microservice.service.*;
import com.jumi.microservice.warehouseout.api.ApiSaledOrderWarehouseOutService;
import com.jumi.microservice.warehouseout.vo.JmSaledOrderCheckGoodsMaterialVo;
import com.jumi.microservice.warehouseout.vo.JmSaledOrderCheckGoodsVo;
import com.jumi.microservice.warehouseout.vo.JmSaledOrderCheckVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author Scw
 * @Date 2020-08-08 15:31
 */
@Service
public class AdminReissueService {

    private static final Logger log = LoggerFactory.getLogger(AdminReissueService.class);
    @Resource
    private ReissueMapper reissueMapper;
    @Resource
    private AfterSealOrderMapper afterSealOrderMapper;
    @Resource
    private AfterSealOrderGoodsMapper afterSealOrderGoodsMapper;
    @Resource
    private CompensationMapper compensationMapper;
    @DubboReference
    private IOrderDubboService iOrderDubboService;
    @DubboReference
    private IOrderService iOrderService;
    @DubboReference
    private IJmSupplierService supplyClient;
    @DubboReference
    private IJmWarehouseService warehouseClient;
    @DubboReference
    ApiSaledOrderWarehouseOutService apiSaledOrderWarehouseOutService;
    @DubboReference
    private BasicDataService basicDataService;
    @DubboReference
    private IUserExternalService iUserExternalService;
    @Resource
    private ExpireTimeConfig expireTimeConfig;

    /**
     * 补发导出excel
     *
     * @param request
     * @return
     */
    public ExportExcelCommonResponse<ExportReissueListResponse> exportExcel(ExportReissueListRequest request) {
        request.checkRequest();
        QueryWrapper<Reissue> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("reissue_type", Arrays.asList(ReissueTypeEnum.REISSUE_GOODS.getCode(), ReissueTypeEnum.REISSUE_MISSED.getCode()));
        queryWrapper.orderByDesc("id");
        //补发审核状态
        if (request.getReissueStatus() != null) {
            queryWrapper.eq("status", request.getReissueStatus());
        }
        //补发原因
        if (request.getReissueReason() != null) {
            queryWrapper.eq("reissue_reason", request.getReissueReason());
        }
        //商品名称
        if (request.getGoodsName() != null && !"".equals(request.getGoodsName())) {
            queryWrapper.like("goods_name", request.getGoodsName());
        }
        //供货商类型：1-供货商【非自营】 2-仓库【自营】
        if (request.getSupplierType() != null) {
            if (request.getSupplierId() != null) {
                queryWrapper.eq("supplier_id", request.getSupplierId());
                if (request.getSupplierType() == com.jumi.microservice.constant.reissue.SupplierTypeEnum.SUPPLIER_TYPE_ONE.getCode().byteValue()) {
                    queryWrapper.eq("self_flag", SelfFlagEnum.SELF_FLAG_NO.getCode());
                }
                if (request.getSupplierType() == com.jumi.microservice.constant.reissue.SupplierTypeEnum.SUPPLIER_TYPE_TWO.getCode().byteValue()) {
                    queryWrapper.eq("self_flag", SelfFlagEnum.SELF_FLAG_YES.getCode());
                }
            }
        }
        //手机号类型：1-购买人手机号 2-收件人手机号
        if (request.getPhoneType() != null) {
            if (request.getPhone() != null && !"".equals(request.getPhone())) {
                if (request.getPhoneType() == PhoneTypeEnum.PHONE_TYPE_BUY.getCode().byteValue()) {
                    queryWrapper.eq("buyer_phone", request.getPhone());
                }
                if (request.getPhoneType() == PhoneTypeEnum.PHONE_TYPE_RECEIVE.getCode().byteValue()) {
                    queryWrapper.eq("receiver_phone", request.getPhone());
                }
            }
        }
        //原订单号
        if (request.getOriginalOrderNo() != null && !"".equals(request.getOriginalOrderNo())) {
            queryWrapper.like("original_order_no", request.getOriginalOrderNo());
        }
        //复选框选择ID
        if (request.getIdStr() != null && !"".equals(request.getIdStr())) {
            queryWrapper.in("id", request.getIdStr().split(","));
        }
        List<Reissue> reissues = reissueMapper.selectList(queryWrapper);
        List<ExportReissueListResponse> result = new ArrayList<>();
        for (Reissue reissue : reissues) {
            ExportReissueListResponse reissueListResponse = new ExportReissueListResponse();
            BeanUtils.copyProperties(reissue, reissueListResponse);
            //类型对照
            ReissueReasonEnum reissueReasonEnum = EnumUtil.getByCode(reissue.getReissueReason().intValue(), ReissueReasonEnum.class);
            if (reissueReasonEnum != null) {
                reissueListResponse.setReissueReasonStr(reissueReasonEnum.getDesc());
            }
            //状态对照
            ReissueStatusEnum reissueStatusEnum = EnumUtil.getByCode(reissue.getStatus().intValue(), ReissueStatusEnum.class);
            if (reissueStatusEnum != null) {
                reissueListResponse.setStatusStr(reissueStatusEnum.getDesc());
            }
            String supplierName = "";
            if (reissue.getSelfFlag() == SelfFlagEnum.SELF_FLAG_NO.getCode().byteValue()) {
                //根据供应商ID查询供应商名称 【仓储服务提供接口】
                ResponseResult<JmSupplierResponse> responseResult = supplyClient.findById(reissue.getSupplierId().longValue());
                Object object = responseResult.getData();
                if (object != null) {
                    JmSupplierResponse jmSupplierResponse = JSON.parseObject(JSON.toJSONString(object), JmSupplierResponse.class);
                    supplierName = jmSupplierResponse.getSupplierCompanyName();
                }
            } else {
                //根据实发仓ID查询实发仓名称 【仓储服务提供接口】
                supplierName = warehouseClient.findById(reissue.getSupplierId().longValue()).getData() != null ? warehouseClient.findById(reissue.getSupplierId().longValue()).getData().getWarehouseName() : "";
            }
            reissueListResponse.setBuyNum(reissue.getGoodsAmount());
            reissueListResponse.setActualNum(reissue.getRealSendAmount());
            reissueListResponse.setSupplierName(supplierName);
            reissueListResponse.setReissueNum(reissue.getGoodsNum());
            result.add(reissueListResponse);
        }
        ExportExcelCommonResponse<ExportReissueListResponse> response = new ExportExcelCommonResponse<>();
        response.setData(result);
        response.setFileName(System.currentTimeMillis() + ".xlsx");
        return response;
    }

    /**
     * 补发列表
     *
     * @param request
     * @return
     */
    public TableDataInfo<ReissueListResponse> reissueList(ReissueListRequest request) {
        QueryWrapper<Reissue> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("reissue_type", Arrays.asList(ReissueTypeEnum.REISSUE_GOODS.getCode(), ReissueTypeEnum.REISSUE_MISSED.getCode()));
        queryWrapper.orderByDesc("id");
        //补发审核状态
        if (request.getReissueStatus() != null) {
            queryWrapper.eq("status", request.getReissueStatus());
        }
        //补发原因
        if (request.getReissueReason() != null) {
            queryWrapper.eq("reissue_reason", request.getReissueReason());
        }
        //商品名称
        if (request.getGoodsName() != null && !"".equals(request.getGoodsName())) {
            queryWrapper.like("goods_name", request.getGoodsName());
        }
        //供货商类型：1-供货商【非自营】 2-仓库【自营】
        if (request.getSupplierType() != null) {
            if (request.getSupplierId() != null) {
                queryWrapper.eq("supplier_id", request.getSupplierId());
                if (request.getSupplierType() == com.jumi.microservice.constant.reissue.SupplierTypeEnum.SUPPLIER_TYPE_ONE.getCode().byteValue()) {
                    queryWrapper.eq("self_flag", SelfFlagEnum.SELF_FLAG_NO.getCode());
                }
                if (request.getSupplierType() == com.jumi.microservice.constant.reissue.SupplierTypeEnum.SUPPLIER_TYPE_TWO.getCode().byteValue()) {
                    queryWrapper.eq("self_flag", SelfFlagEnum.SELF_FLAG_YES.getCode());
                }
            }
        }
        //手机号类型：1-购买人手机号 2-收件人手机号
        if (request.getPhoneType() != null) {
            if (request.getPhone() != null && !"".equals(request.getPhone())) {
                if (request.getPhoneType() == PhoneTypeEnum.PHONE_TYPE_BUY.getCode().byteValue()) {
                    queryWrapper.eq("buyer_phone", request.getPhone());
                }
                if (request.getPhoneType() == PhoneTypeEnum.PHONE_TYPE_RECEIVE.getCode().byteValue()) {
                    queryWrapper.eq("receiver_phone", request.getPhone());
                }
            }
        }
        //原订单号
        if (request.getOriginalOrderNo() != null && !"".equals(request.getOriginalOrderNo())) {
            queryWrapper.like("original_order_no", request.getOriginalOrderNo());
        }
        IPage<Reissue> page = new Page<>(request.getPageNum(), request.getPageSize());
        page = reissueMapper.selectPage(page, queryWrapper);
        List<Reissue> reissues = page.getRecords();
        List<ReissueListResponse> result = new ArrayList<>();
        if (reissues.size() > 0) {
            for (Reissue reissue : reissues) {
                ReissueListResponse reissueListResponse = new ReissueListResponse();
                BeanUtils.copyProperties(reissue, reissueListResponse);
                //补发类型对照
                if (reissue.getReissueType() == ReissueTypeEnum.REISSUE_REPLACE.getCode().byteValue()) {
                    ReplacementReasonEnum replacementReasonEnum = EnumUtil.getByCode(reissue.getReissueReason().intValue(), ReplacementReasonEnum.class);
                    if (replacementReasonEnum != null) {
                        reissueListResponse.setReissueReasonStr(replacementReasonEnum.getDesc());
                    }
                } else {
                    ReissueReasonEnum reissueReasonEnum = EnumUtil.getByCode(reissue.getReissueReason().intValue(), ReissueReasonEnum.class);
                    if (reissueReasonEnum != null) {
                        reissueListResponse.setReissueReasonStr(reissueReasonEnum.getDesc());
                    }
                }
                String supplierName = "";
                if (reissue.getSelfFlag() == SelfFlagEnum.SELF_FLAG_NO.getCode().byteValue()) {
                    //根据供应商ID查询供应商名称 【仓储服务提供接口】
                    ResponseResult<JmSupplierResponse> responseResult = supplyClient.findById(reissue.getSupplierId().longValue());
                    Object object = responseResult.getData();
                    if (object != null) {
                        JmSupplierResponse jmSupplierResponse = JSON.parseObject(JSON.toJSONString(object), JmSupplierResponse.class);
                        supplierName = jmSupplierResponse.getSupplierCompanyName();
                    }
                } else {
                    //根据实发仓ID查询实发仓名称 【仓储服务提供接口】
                    supplierName = warehouseClient.findById(reissue.getSupplierId().longValue()).getData() != null ? warehouseClient.findById(reissue.getSupplierId().longValue()).getData().getWarehouseName() : "";
                }
                reissueListResponse.setBuyNum(reissue.getGoodsAmount());
                reissueListResponse.setActualNum(reissue.getRealSendAmount());
                reissueListResponse.setSupplierName(supplierName);
                reissueListResponse.setReissueNum(reissue.getGoodsNum());
                result.add(reissueListResponse);
            }
        }
        TableDataInfo<ReissueListResponse> dataInfo = new TableDataInfo<>();
        dataInfo.setRows(result);
        dataInfo.setTotal(page.getTotal());
        return dataInfo;
    }

    /**
     * 补发添加
     *
     * @param reissueAddRequest
     * @return
     */
    @Transactional
    public Boolean addReissue(ReissueAddRequest reissueAddRequest) {
        log.debug("【补发添加】进入-->");
        Long operatorId = reissueAddRequest.getOperatorId();
        String operatorName = reissueAddRequest.getOperatorName();
        boolean postageFlag = false;
        /*
         * 根据订单ID查询订单状态【订单表】
         * 订单状态：0-已取消、1-待付款、2-待发货、3-待收货、4-已完成
         * 发起退货：3-待收货、4-已完成
         * 补发：3-待收货、4-已完成
         * 补发漏发：3-待收货、4-已完成
         * 换货：3-待收货、4-已完成
         * 补偿：3-待收货、4-已完成
         * 补邮：3-待收货、4-已完成
         */
        //根据订单ID查询订单状态【订单表】
        Integer orderStatus = iOrderService.getOrderStatus(reissueAddRequest.getOriginalOrderId());
        if (orderStatus != null) {
            //Integer[] notAllowArr = {0, 1, 2};
            Integer[] notAllowArr = {
                    OrderStatusEnum.CANCEL.getCode().intValue(),
                    OrderStatusEnum.READY_TO_PAY.getCode().intValue(),
                    OrderStatusEnum.READY_TO_SHIP.getCode().intValue()
            };
            if (Arrays.asList(notAllowArr).contains(orderStatus)) {
                throw new BaseException(ReissueExceptionEnum.ORDER_STATUS_NOT_ALLOW.getCode(), ReissueExceptionEnum.ORDER_STATUS_NOT_ALLOW.getMessage());
            }
            //订单状态：3-待收货、4-已完成
            if (orderStatus == OrderStatusEnum.READY_TO_RECEIVE.getCode().intValue() || orderStatus == OrderStatusEnum.COMPLETED.getCode().intValue()) {
                //收货时间
                Date confirmTime = iOrderService.getConfirmTime(reissueAddRequest.getOriginalOrderId());
                if (confirmTime != null) {
                    //收货时间 + 8 < 当前时间
                    if (DateUtil.getDateAfterDay(confirmTime, Integer.parseInt(expireTimeConfig.getDiffDayOne())).before(new Date())) {
                        throw new BaseException(RefundGoodsExceptionEnum.ORDER_OVER_TIME.getCode(), RefundGoodsExceptionEnum.ORDER_OVER_TIME.getMessage());
                    }
                }
            }
        }

        /*
         * 根据订单ID/商品ID查询 商品实发数量、售后状态、退货数量/补发数量【订单商品表】
         */
        OrderStatusAfterSealResponse orderStatusAfterSealResponse = iOrderService.getStatusAfterSeal(reissueAddRequest.getOriginalOrderId(), reissueAddRequest.getGoodsId());
        if (orderStatusAfterSealResponse != null) {
            int goodsNum = orderStatusAfterSealResponse.getRealSendAmount();
            int returnNum = orderStatusAfterSealResponse.getReturnCount();
            int refundNum = reissueAddRequest.getGoodsNum();
            int totalNum = returnNum + refundNum;
            if (totalNum > goodsNum) {
                throw new BaseException(ReissueExceptionEnum.GOODS_STATUS_MAX_NUM.getCode(), ReissueExceptionEnum.GOODS_STATUS_MAX_NUM.getMessage());
            }
            /*
             * 售后状态:
             *      0-正常 1-已退款
             *      2-退货审核中 3-已退货退款 4-退货退款拒绝
             *      5-补发审核中 6-已补发 7-补发拒绝
             *      8-补偿审核中 9-已补偿 10-补偿拒绝
             *      11-补邮审核中 12-已补邮费 13-补邮拒绝
             *      14-换货申请中 15-换货同意  16-换货拒绝
             *      17-补发漏发审核中 18-已补发漏发 19-补发漏发拒绝
             * 发起退货：0-正常、4-退货退款拒绝、7-补发拒绝、10-补偿拒绝、16-换货拒绝、19-补发漏发拒绝
             * 补发：0-正常、4-退货退款拒绝、7-补发拒绝、10-补偿拒绝、16-换货拒绝、19-补发漏发拒绝
             * 补偿：0-正常、4-退货退款拒绝、7-补发拒绝、10-补偿拒绝、16-换货拒绝、19-补发漏发拒绝
             * 补邮：2-退货审核中、3-已退货退款、13-补邮拒绝、14-换货申请中、15-换货同意
             * 换货：0-正常、4-退货退款拒绝、7-补发拒绝、10-补偿拒绝、16-换货拒绝、19-补发漏发拒绝
             * 补发漏发：0-正常、4-退货退款拒绝、7-补发拒绝、10-补偿拒绝、16-换货拒绝、19-补发漏发拒绝
             */
            //Integer[] notAfterSaleArr = {1, 2, 3, 5, 6, 8, 9, 11, 12, 13, 14, 15，17，18};
            Integer[] notAfterSaleArr = {
                    AfterSaleStatusEnum.REFUND.getCode(),
                    AfterSaleStatusEnum.REFUND_GOODS_APPLY.getCode(),
                    AfterSaleStatusEnum.REFUND_GOODS_AGREE.getCode(),
                    AfterSaleStatusEnum.REISSUE_APPLY.getCode(),
                    AfterSaleStatusEnum.REISSUE_AGREE.getCode(),
                    AfterSaleStatusEnum.COMPENSATION_APPLY.getCode(),
                    AfterSaleStatusEnum.COMPENSATION_AGREE.getCode(),
                    AfterSaleStatusEnum.COMPENSATION_POSTAGE_APPLY.getCode(),
                    AfterSaleStatusEnum.COMPENSATION_POSTAGE_AGREE.getCode(),
                    AfterSaleStatusEnum.COMPENSATION_POSTAGE_REFUSE.getCode(),
                    AfterSaleStatusEnum.REPLACE_APPLY.getCode(),
                    AfterSaleStatusEnum.REPLACE_AGREE.getCode(),
                    AfterSaleStatusEnum.REISSUE_MISSED_APPLY.getCode(),
                    AfterSaleStatusEnum.REISSUE_MISSED_AGREE.getCode()
            };
            Integer afterSaleStatus = orderStatusAfterSealResponse.getAfterSealStatus().intValue();
            if (Arrays.asList(notAfterSaleArr).contains(afterSaleStatus)) {
                throw new BaseException(ReissueExceptionEnum.GOODS_STATUS_NOT_ALLOW.getCode(), ReissueExceptionEnum.GOODS_STATUS_NOT_ALLOW.getMessage());
            }
        }
        String generateOrderSn;
        //售后单号 补发、漏发、换货
        if (reissueAddRequest.getReissueType() == ReissueTypeEnum.REISSUE_GOODS.getCode().byteValue()) {
            generateOrderSn = this.generateOrderSnBf();
        } else if (reissueAddRequest.getReissueType() == ReissueTypeEnum.REISSUE_MISSED.getCode().byteValue()) {
            generateOrderSn = this.generateOrderSnLf();
        } else {
            generateOrderSn = this.generateOrderSnHh();
        }
        boolean res = false;
        Reissue reissue = new Reissue();
        BeanUtils.copyProperties(reissueAddRequest, reissue);
        reissue.setPromoterId(operatorId);
        reissue.setPromoterName(operatorName);
        reissue.setReissueOrderNo(generateOrderSn);
        /*
         * 自营标识: 0-非自营 1-自营
         * 0-非自营--添加并通过审核
         * 1-自营--添加等待审核
         *
         */
        boolean isSelf = reissueAddRequest.getSelfFlag() == SelfFlagEnum.SELF_FLAG_YES.getCode().intValue();
        if (reissueAddRequest.getSelfFlag() == SelfFlagEnum.SELF_FLAG_NO.getCode().intValue()) {
            reissue.setStatus(ReissueStatusEnum.STATUS_PASSED.getCode().byteValue());
            reissue.setCheckTime(new Date());
            reissue.setCheckOperatorId(operatorId);
            reissue.setCheckOperatorName(operatorName);
        }
        //根据订单ID和商品ID查询原支付订单信息
        OrderGoodsServiceDetailsRequest orderGoodsServiceDetailsRequest = new OrderGoodsServiceDetailsRequest();
        orderGoodsServiceDetailsRequest.setOrderId(reissueAddRequest.getOriginalOrderId());
        orderGoodsServiceDetailsRequest.setGoodsId(reissueAddRequest.getGoodsId());
        OrderGoodsServiceDetailsResponse orderGoodsServiceDetailsResponse = iOrderService.findOrderGoodsDetails(orderGoodsServiceDetailsRequest);
        if (orderGoodsServiceDetailsResponse == null) {
            throw new BaseException(500, "订单信息有误！");
        }
        reissue.setOrderCreateTime(orderGoodsServiceDetailsResponse.getCreateTime());
        Integer supplierId = isSelf ? orderGoodsServiceDetailsResponse.getRealWarehouse() : orderGoodsServiceDetailsResponse.getSupplierId();
        reissue.setSupplierId(supplierId);
        reissue.setGoodsName(orderGoodsServiceDetailsResponse.getGoodsName());
        reissue.setGoodsAmount(orderGoodsServiceDetailsResponse.getGoodsAmount());
        reissue.setRealSendAmount(orderGoodsServiceDetailsResponse.getRealSendAmount());
        reissue.setGoodsPrice(orderGoodsServiceDetailsResponse.getGoodsPrice());
        reissue.setGoodsPic(orderGoodsServiceDetailsResponse.getGoodsCoverImg());
        //根据用户ID查询手机号【用户服务提供接口】
        UserExternalResponse userExternalResponse = iUserExternalService.getUserByUid(orderGoodsServiceDetailsResponse.getBuyerId().intValue());
        String buyerPhone;
        if (userExternalResponse != null) {
            buyerPhone = userExternalResponse.getMobile();
            reissue.setBuyerPhone(buyerPhone);
        }
        String generateOrderSnSh = "";
        if (reissueMapper.insert(reissue) > 0) {
            /*
             * 非自营商品，直接创建订单
             */
            if (!isSelf) {
                log.debug("【补发添加】 非自营商品，直接创建订单");
                //创建售后订单
                AfterSealOrder afterSealOrder = new AfterSealOrder();
                //补发/补发漏发/换货ID
                afterSealOrder.setReissueId(reissue.getId());
                //补发/补发漏发/换货名称
                afterSealOrder.setReissueNo(reissue.getReissueOrderNo());
                //补发/补发漏发/换货备注
                afterSealOrder.setReissueRemark(reissue.getRemark());
                //补发原因: 0-做单/登记失误 1-仓储发货原因 2-快递原因 3-产品原因 4-顾客自身原因
                afterSealOrder.setReissueReason(reissue.getReissueReason());
                //发起人姓名
                afterSealOrder.setPromoterName(reissue.getPromoterName());
                //原订单ID
                afterSealOrder.setOriginalOrderId(orderGoodsServiceDetailsResponse.getId());
                //原订单编号
                afterSealOrder.setOriginalOrderNo(orderGoodsServiceDetailsResponse.getOrderNo());
                //售后订单编号
                generateOrderSnSh = this.generateOrderSnSh();
                afterSealOrder.setOrderNo(generateOrderSnSh);
                afterSealOrder.setBuyerId(orderGoodsServiceDetailsResponse.getBuyerId());
                afterSealOrder.setBuyerRole(orderGoodsServiceDetailsResponse.getBuyerRole());
                //订单团购价 = 商品团购价 * 商品数量
                BigDecimal orderPromotionAmount = orderGoodsServiceDetailsResponse.getGoodsPromotionPrice().multiply(BigDecimal.valueOf(orderGoodsServiceDetailsResponse.getGoodsAmount()));
                afterSealOrder.setOrderPromotionAmount(orderPromotionAmount);
                //用户级别：1、团购用户 2、店长 3、优秀店长 4、金牌推广商
                if (orderGoodsServiceDetailsResponse.getBuyerRole() == ReissueUserRoleEnum.USER_ROLE_PROMOTION.getCode().byteValue()) {
                    afterSealOrder.setOrderAmount(orderGoodsServiceDetailsResponse.getGoodsPromotionPrice());
                } else if (orderGoodsServiceDetailsResponse.getBuyerRole() == ReissueUserRoleEnum.USER_ROLE_PLATINUM.getCode().byteValue()) {
                    afterSealOrder.setOrderAmount(orderGoodsServiceDetailsResponse.getGoodsPlatinumPrice());
                } else if (orderGoodsServiceDetailsResponse.getBuyerRole() == ReissueUserRoleEnum.USER_ROLE_DIAMONDS.getCode().byteValue()) {
                    afterSealOrder.setOrderAmount(orderGoodsServiceDetailsResponse.getGoodsDiamondsPrice());
                } else if (orderGoodsServiceDetailsResponse.getBuyerRole() == ReissueUserRoleEnum.USER_ROLE_KING.getCode().byteValue()) {
                    afterSealOrder.setOrderAmount(orderGoodsServiceDetailsResponse.getGoodsKingPrice());
                }
                afterSealOrder.setOrderType(reissueAddRequest.getReissueType());
                String receiverName = reissueAddRequest.getReceiverName();
                if (receiverName == null || "".equals(receiverName) || receiverName.length() == 0) {
                    receiverName = orderGoodsServiceDetailsResponse.getReceiverName();
                }
                afterSealOrder.setReceiverName(receiverName);
                String receiverPhone = reissueAddRequest.getReceiverPhone();
                if (receiverPhone == null || "".equals(receiverPhone) || receiverPhone.length() == 0) {
                    receiverPhone = orderGoodsServiceDetailsResponse.getReceiverPhone();
                }
                afterSealOrder.setReceiverPhone(receiverPhone);
                String receiverAddress = reissueAddRequest.getReceiverAddress();
                if (receiverAddress == null || "".equals(receiverAddress) || receiverAddress.length() == 0) {
                    receiverAddress = orderGoodsServiceDetailsResponse.getReceiverAddress();
                }
                afterSealOrder.setReceiverAddress(receiverAddress);
                //海外商品
                if (orderGoodsServiceDetailsResponse.getIsImport() == ImportFlagEnum.IMPORT_FLAG_YES.getCode().byteValue()) {
                    //收件人真实姓名
                    afterSealOrder.setReceiverRealName(orderGoodsServiceDetailsResponse.getReceiverRealName());
                    //收货人证件号
                    afterSealOrder.setReceiverCardNo(orderGoodsServiceDetailsResponse.getReceiverCardNo());
                }
                if (afterSealOrderMapper.insert(afterSealOrder) > 0) {
                    //获取添加主键ID
                    int orderId = afterSealOrder.getId();
                    //创建售后订单商品
                    AfterSealOrderGoods afterSealOrderGoods = new AfterSealOrderGoods();
                    afterSealOrderGoods.setOrderId(orderId);
                    afterSealOrderGoods.setGoodsId(orderGoodsServiceDetailsResponse.getGoodsId());
                    afterSealOrderGoods.setGoodsName(orderGoodsServiceDetailsResponse.getGoodsName());
                    afterSealOrderGoods.setGoodsAmount(reissue.getGoodsNum());
                    afterSealOrderGoods.setGoodsPromotionPrice(orderGoodsServiceDetailsResponse.getGoodsPromotionPrice());
                    afterSealOrderGoods.setGoodsPlatinumPrice(orderGoodsServiceDetailsResponse.getGoodsPlatinumPrice());
                    afterSealOrderGoods.setGoodsDiamondsPrice(orderGoodsServiceDetailsResponse.getGoodsDiamondsPrice());
                    afterSealOrderGoods.setGoodsKingPrice(orderGoodsServiceDetailsResponse.getGoodsKingPrice());
                    afterSealOrderGoods.setGoodsPrice(orderGoodsServiceDetailsResponse.getGoodsPrice());
                    afterSealOrderGoods.setGoodsCostPrice(orderGoodsServiceDetailsResponse.getGoodsCostPrice());
                    afterSealOrderGoods.setGoodsCoverImg(orderGoodsServiceDetailsResponse.getGoodsCoverImg());
                    afterSealOrderGoods.setSelfFlag(orderGoodsServiceDetailsResponse.getSelfFlag());
                    afterSealOrderGoods.setSupplierId(orderGoodsServiceDetailsResponse.getSupplierId());
                    afterSealOrderGoods.setWarehouse(orderGoodsServiceDetailsResponse.getRealWarehouse());
                    afterSealOrderGoods.setWarehouseSn(orderGoodsServiceDetailsResponse.getWarehouseSn());
                    afterSealOrderGoods.setIsImport(orderGoodsServiceDetailsResponse.getIsImport());
                    afterSealOrderGoods.setGoodsWeight(orderGoodsServiceDetailsResponse.getGoodsWeight());
                    afterSealOrderGoodsMapper.insert(afterSealOrderGoods);
                }
            } else {
                log.debug("【补发添加】 自营商品，添加物料售后订单信息");
                /*
                 * 自营商品，添加物料售后订单信息
                 */
                /****************************添加物料售后订单信息************************/
                JmSaledOrderCheckVo jmSaledOrderCheckVo = new JmSaledOrderCheckVo();
                jmSaledOrderCheckVo.setSaledOrderCode(reissue.getReissueOrderNo());
                jmSaledOrderCheckVo.setOldOrderCode(reissue.getOriginalOrderNo());
                ReissueTypeEnum reissueTypeEnum = EnumUtil.getByCode(reissue.getReissueType().intValue(), ReissueTypeEnum.class);
                if (reissueTypeEnum != null) {
                    jmSaledOrderCheckVo.setSaledType(reissueTypeEnum.getDesc());
                }
                jmSaledOrderCheckVo.setSelledRemark(reissue.getRemark());
                if (userExternalResponse != null) {
                    jmSaledOrderCheckVo.setBuyerMessage(userExternalResponse.getNickName() + " " + userExternalResponse.getMobile());
                }
                jmSaledOrderCheckVo.setBuyerDetail(reissue.getReceiverName() + " " + reissue.getReceiverPhone() + " " + reissue.getReceiverAddress());
                //获取物料信息
                List<Long> skuIdList = new ArrayList<>();
                skuIdList.add(reissue.getGoodsId().longValue());
                List<GoodsSkuMaterialDTO> materialDtoList = basicDataService.getMaterialSkuRelationshipByIds(skuIdList);
                log.debug("【补发添加】 获取到的物料信息数据 [{}]", JSON.toJSONString(materialDtoList));
                if (materialDtoList.size() > 0) {
                    List<JmSaledOrderCheckGoodsVo> goodsVoList = new ArrayList<>();
                    for (GoodsSkuMaterialDTO goodsSkuMaterialDTO : materialDtoList) {
                        for (MaterialSkuRelationshipDTO materialSkuRelationshipDTO : goodsSkuMaterialDTO.getMaterialSkuRelationship()) {
                            JmSaledOrderCheckGoodsVo jmSaledOrderCheckGoodsVo = new JmSaledOrderCheckGoodsVo();
                            jmSaledOrderCheckGoodsVo.setGoodsName(materialSkuRelationshipDTO.getMaterialSpuName());
                            jmSaledOrderCheckGoodsVo.setGoodsCode(materialSkuRelationshipDTO.getMaterialSpuCode());
                            //根据实发仓ID查询实发仓名称 【仓储服务提供接口】
                            String realWarehouse = warehouseClient.findById(orderGoodsServiceDetailsResponse.getRealWarehouse().longValue()).getData() != null ? warehouseClient.findById(orderGoodsServiceDetailsResponse.getRealWarehouse().longValue()).getData().getWarehouseName() : "";
                            log.debug("【补发添加】 根据实发仓ID查询实发仓名称 [{}]", realWarehouse);
                            jmSaledOrderCheckGoodsVo.setShouldSendWarehouse(realWarehouse);
                            /**********************************售后申请商品的物料集合***********************************/
                            List<JmSaledOrderCheckGoodsMaterialVo> materialVoList = new ArrayList<>();
                            JmSaledOrderCheckGoodsMaterialVo jmSaledOrderCheckGoodsMaterialVo = new JmSaledOrderCheckGoodsMaterialVo();
                            jmSaledOrderCheckGoodsMaterialVo.setMaterialCode(materialSkuRelationshipDTO.getMaterialSkuCode());
                            //jmSaledOrderCheckGoodsMaterialVo.setSpecName(materialSkuRelationshipDTO.getMaterialSpuName());
                            jmSaledOrderCheckGoodsMaterialVo.setWeight(materialSkuRelationshipDTO.getWeight().doubleValue());
                            jmSaledOrderCheckGoodsMaterialVo.setNumbers(reissue.getGoodsNum());
                            //换货
                            if (reissueAddRequest.getReissueType() == ReissueTypeEnum.REISSUE_REPLACE.getCode().byteValue()) {
                                ReplacementReasonEnum replacementReasonEnum = EnumUtil.getByCode(reissue.getReissueReason().intValue(), ReplacementReasonEnum.class);
                                if (replacementReasonEnum != null) {
                                    jmSaledOrderCheckGoodsMaterialVo.setSaledReason(replacementReasonEnum.getDesc());
                                }
                            } else {
                                ReissueReasonEnum reissueReasonEnum = EnumUtil.getByCode(reissue.getReissueReason().intValue(), ReissueReasonEnum.class);
                                if (reissueReasonEnum != null) {
                                    jmSaledOrderCheckGoodsMaterialVo.setSaledReason(reissueReasonEnum.getDesc());
                                }
                            }
                            materialVoList.add(jmSaledOrderCheckGoodsMaterialVo);
                            jmSaledOrderCheckGoodsVo.setMaterialVoList(materialVoList);
                            /**********************************售后申请商品的物料集合***********************************/
                            goodsVoList.add(jmSaledOrderCheckGoodsVo);
                        }
                    }
                    jmSaledOrderCheckVo.setGoodsVoList(goodsVoList);
                }
                try {
                    log.debug("【补发添加】 调用物料服务审核添加--> [{}]", JSON.toJSONString(jmSaledOrderCheckVo));
                    apiSaledOrderWarehouseOutService.add(jmSaledOrderCheckVo);
                } catch (Exception e) {
                    //e.printStackTrace();
                    log.error("【补发添加】 调用物料服务审核添加出错 [{}]", e.getMessage());
//                    e.getMessage();
                }
                /****************************添加物料售后订单信息************************/
            }
            /*
             * 订单商品表更新售后状态
             * 售后状态:
             *      0-正常 1-已退款
             *      2-退货审核中 3-已退货退款 4-退货退款拒绝
             *      5-补发审核中 6-已补发 7-补发拒绝
             *      8-补偿审核中 9-已补偿 10-补偿拒绝
             *      11-补邮审核中 12-已补邮费 13-补邮拒绝
             *      14-换货申请中 15-换货同意  16-换货拒绝
             *      17-补发漏发审核中 18-已补发漏发 19-补发漏发拒绝
             *      补发：after_seal_status = 5、after_seal_status = 6
             *      补发漏发：after_seal_status = 17、after_seal_status = 18
             *      换货：after_seal_status = 14、after_seal_status = 15
             */
            //isSelf==true，添加等待审核、反之 添加并审核通过
            int afterSealStatus = 0;
            if (reissueAddRequest.getReissueType() == ReissueTypeEnum.REISSUE_GOODS.getCode().byteValue()) {
                afterSealStatus = isSelf ? AfterSaleStatusEnum.REISSUE_APPLY.getCode() : AfterSaleStatusEnum.REISSUE_AGREE.getCode();
            } else if (reissueAddRequest.getReissueType() == ReissueTypeEnum.REISSUE_MISSED.getCode().byteValue()) {
                afterSealStatus = isSelf ? AfterSaleStatusEnum.REISSUE_MISSED_APPLY.getCode() : AfterSaleStatusEnum.REISSUE_MISSED_AGREE.getCode();
            } else {
                afterSealStatus = isSelf ? AfterSaleStatusEnum.REPLACE_APPLY.getCode() : AfterSaleStatusEnum.REPLACE_AGREE.getCode();
            }
            //非自营商品，直接更新数量
            if (!isSelf) {
                UpdateReturnInfoRequest updateReturnInfoRequest = new UpdateReturnInfoRequest();
                updateReturnInfoRequest.setOrderId(reissueAddRequest.getOriginalOrderId());
                updateReturnInfoRequest.setGoodsId(reissueAddRequest.getGoodsId());
                updateReturnInfoRequest.setReturnCount(reissueAddRequest.getGoodsNum());
                updateReturnInfoRequest.setReturnPrice(BigDecimal.valueOf(0));
                updateReturnInfoRequest.setReturnPostage(BigDecimal.valueOf(0));
                log.debug("【补发添加】 非自营商品，直接更新数量 [{}]", JSON.toJSONString(updateReturnInfoRequest));
                iOrderService.updateReturnInfo(updateReturnInfoRequest);
                //换货
                if (reissueAddRequest.getReissueType() == ReissueTypeEnum.REISSUE_REPLACE.getCode().byteValue()) {
                    /*
                     * 补偿邮费
                     * 默认锁定执行解锁操作
                     * 是否锁定: 0-否 1-是
                     */
                    QueryWrapper<Compensation> queryWrapperCompensation = new QueryWrapper<>();
                    queryWrapperCompensation.eq("refund_id", reissue.getId());
                    queryWrapperCompensation.eq("lock_flag", LockFlagEnum.LOCK_FLAG_YES.getCode());
                    queryWrapperCompensation.eq("after_sale_type", AfterSaleEnum.AFTER_SALE_BCYF.getCode());
                    queryWrapperCompensation.eq("postage_type", PostageTypeEnum.POSTAGE_TYPE_REISSUE.getCode());
                    queryWrapperCompensation.eq("check_status", CheckStatusEnum.CHECK_STATUS_WAIT.getCode());
                    queryWrapperCompensation.eq("original_order_id", reissue.getOriginalOrderId());
                    queryWrapperCompensation.eq("compensation_goods_id", reissue.getGoodsId());
                    queryWrapperCompensation.eq("buyer_id", reissue.getBuyerId());
                    queryWrapperCompensation.orderByDesc("id");
                    queryWrapperCompensation.last("limit 1");
                    Compensation compensation = compensationMapper.selectOne(queryWrapperCompensation);
                    if (compensation != null) {
                        compensation.setLockFlag(LockFlagEnum.LOCK_FLAG_NO.getCode().byteValue());
                        compensationMapper.updateById(compensation);
                        postageFlag = true;
                    }

                }
                if(postageFlag) {
                    afterSealStatus = AfterSaleStatusEnum.COMPENSATION_POSTAGE_APPLY.getCode();
                }
            }
            UpdateAfterSealStatusRequest updateAfterSealStatusRequest = new UpdateAfterSealStatusRequest();
            updateAfterSealStatusRequest.setOrderId(reissueAddRequest.getOriginalOrderId());
            updateAfterSealStatusRequest.setGoodsId(reissueAddRequest.getGoodsId());
            updateAfterSealStatusRequest.setAfterSealStatus((byte) afterSealStatus);
            iOrderService.updateAfterSealStatus(updateAfterSealStatusRequest);
            /*
             * 操作日志表插入相关信息
             */
            String logInfo;
            if (reissue.getReissueType() == ReissueTypeEnum.REISSUE_GOODS.getCode().byteValue()) {
                if (!isSelf) {
                    logInfo = "售后处理-同意补发；售后订单编号：" + generateOrderSnSh;
                } else {
                    logInfo = "发起补发：" + reissue.getGoodsName() + " " + reissueAddRequest.getGoodsNum();
                }
            } else if (reissue.getReissueType() == ReissueTypeEnum.REISSUE_MISSED.getCode().byteValue()) {
                if (!isSelf) {
                    logInfo = "售后处理-同意补发-漏发；售后订单编号：" + generateOrderSnSh;
                } else {
                    logInfo = "发起补发-漏发：" + reissue.getGoodsName() + " " + reissueAddRequest.getGoodsNum();
                }
            } else {
                if (!isSelf) {
                    logInfo = "售后处理-同意换货；售后订单编号：" + generateOrderSnSh;
                } else {
                    logInfo = "发起换货：" + reissue.getGoodsName() + " " + reissueAddRequest.getGoodsNum();
                }
            }
            log.debug("【补发添加】 添加日志信息 [{}]", logInfo);
            //用户标识，1 前端用户， 2 后端管理员
            Byte userFlag = CancelUserFlagEnum.USER_FLAG_ADMIN.getCode().byteValue();
            OrderLogRequest orderLogRequest = new OrderLogRequest();
            orderLogRequest.setLog(logInfo);
            orderLogRequest.setOperatorId(operatorId);
            orderLogRequest.setOperatorName(operatorName);
            orderLogRequest.setUserFlag(userFlag);
            orderLogRequest.setOrderSn(reissueAddRequest.getOriginalOrderNo());
            Boolean isAddLog = iOrderDubboService.addOrderLog(orderLogRequest);
            if (isAddLog) {
                res = true;
            }
        }
        return res;
    }

    /**
     * 自营--补发取消
     * 补发状态/换货状态--待审核
     *
     * @param reissueCancelRequest
     * @param reissueOperateRequest
     * @return
     */
    @Transactional
    public Boolean cancelReissue(ReissueCancelRequest reissueCancelRequest, ReissueOperateRequest reissueOperateRequest) {
        Long operatorId = reissueCancelRequest.getOperatorId();
        String operatorName = reissueCancelRequest.getOperatorName();

        boolean res = false;
        int reissueId = reissueOperateRequest.getId();
        //查询信息
        QueryWrapper<Reissue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", reissueId);
        queryWrapper.eq("status", ReissueStatusEnum.STATUS_WAIT.getCode());
        queryWrapper.eq("reissue_type", reissueOperateRequest.getReissueType());
        Reissue reissue = reissueMapper.selectOne(queryWrapper);
        if (reissue == null) {
            throw new BaseException(ReissueExceptionEnum.INFO_NO_EXIST.getCode(), ReissueExceptionEnum.INFO_NO_EXIST.getMessage());
        }
        //审核状态更新
        reissue.setStatus(ReissueStatusEnum.STATUS_CANCEL.getCode().byteValue());
        reissue.setCancelRemark(reissueCancelRequest.getCancelRemark());
        reissue.setCancelTime(new Date());
        reissue.setCancelOperatorId(operatorId);
        reissue.setCancelOperatorName(operatorName);
        if (reissueMapper.updateById(reissue) > 0) {
            /*
             * 订单商品表更新售后状态
             * 售后状态:
             *      0-正常 1-已退款
             *      2-退货审核中 3-已退货退款 4-退货退款拒绝
             *      5-补发审核中 6-已补发 7-补发拒绝
             *      8-补偿审核中 9-已补偿 10-补偿拒绝
             *      11-补邮审核中 12-已补邮费 13-补邮拒绝
             *      14-换货申请中 15-换货同意  16-换货拒绝
             *      17-补发漏发审核中 18-已补发漏发 19-补发漏发拒绝
             * after_seal_status = 0
             */
            //int afterSealStatus = 0;
            int afterSealStatus = AfterSaleStatusEnum.NORMAL.getCode();
            UpdateAfterSealStatusRequest updateAfterSealStatusRequest = new UpdateAfterSealStatusRequest();
            updateAfterSealStatusRequest.setOrderId(reissue.getOriginalOrderId());
            updateAfterSealStatusRequest.setGoodsId(reissue.getGoodsId());
            updateAfterSealStatusRequest.setAfterSealStatus((byte) afterSealStatus);
            iOrderService.updateAfterSealStatus(updateAfterSealStatusRequest);

            /*
             * 供应链取消售后订单
             */
            apiSaledOrderWarehouseOutService.cancelSaledOrderCode(reissue.getReissueOrderNo(), operatorName);
            //换货
            if (reissue.getReissueType() == ReissueTypeEnum.REISSUE_REPLACE.getCode().byteValue()) {
                /*
                 * 补偿邮费
                 * 默认锁定执行解锁操作
                 * 是否锁定: 0-否 1-是
                 */
                QueryWrapper<Compensation> queryWrapperCompensation = new QueryWrapper<>();
                queryWrapperCompensation.eq("refund_id", reissue.getId());
                queryWrapperCompensation.eq("lock_flag", LockFlagEnum.LOCK_FLAG_YES.getCode());
                queryWrapperCompensation.eq("after_sale_type", AfterSaleEnum.AFTER_SALE_BCYF.getCode());
                queryWrapperCompensation.eq("postage_type", PostageTypeEnum.POSTAGE_TYPE_REISSUE.getCode());
                queryWrapperCompensation.eq("check_status", CheckStatusEnum.CHECK_STATUS_WAIT.getCode());
                queryWrapperCompensation.eq("original_order_id", reissue.getOriginalOrderId());
                queryWrapperCompensation.eq("compensation_goods_id", reissue.getGoodsId());
                queryWrapperCompensation.eq("buyer_id", reissue.getBuyerId());
                queryWrapperCompensation.orderByDesc("id");
                queryWrapperCompensation.last("limit 1");
                Compensation compensation = compensationMapper.selectOne(queryWrapperCompensation);
                if (compensation != null) {
                    compensation.setCheckStatus(CheckStatusEnum.CHECK_STATUS_REFUSE.getCode().byteValue());
                    compensation.setCheckTime(new Date());
                    compensation.setCheckOperatorId(operatorId);
                    compensation.setCheckOperatorName(operatorName);
                    compensation.setCheckRemark("售后处理-取消换货订单");
                    compensationMapper.updateById(compensation);
                }
            }
            /*
             * 操作日志表插入相关信息
             */
            String logInfo = "售后处理-取消";
            if (reissue.getReissueType() == ReissueTypeEnum.REISSUE_GOODS.getCode().byteValue()) {
                logInfo += "补发";
            } else if (reissue.getReissueType() == ReissueTypeEnum.REISSUE_MISSED.getCode().byteValue()) {
                logInfo += "补发-漏发";
            } else {
                logInfo += "换货";
            }
            //用户标识，1 前端用户， 2 后端管理员
            Byte userFlag = CancelUserFlagEnum.USER_FLAG_ADMIN.getCode().byteValue();
            OrderLogRequest orderLogRequest = new OrderLogRequest();
            orderLogRequest.setLog(logInfo);
            orderLogRequest.setOperatorId(operatorId);
            orderLogRequest.setOperatorName(operatorName);
            orderLogRequest.setUserFlag(userFlag);
            orderLogRequest.setOrderSn(reissue.getOriginalOrderNo());
            Boolean isAddLog = iOrderDubboService.addOrderLog(orderLogRequest);
            if (isAddLog) {
                res = true;
            }
        }
        return res;
    }

    /**
     * 补发详情
     *
     * @param reissueOperateRequest
     * @return
     */
    public ReissueInfoResponse reissueInfo(ReissueOperateRequest reissueOperateRequest) {
        int reissueId = reissueOperateRequest.getId();
        //查询信息
        QueryWrapper<Reissue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reissue_type", reissueOperateRequest.getReissueType());
        queryWrapper.eq("id", reissueId);
        Reissue reissue = reissueMapper.selectOne(queryWrapper);
        if (reissue == null) {
            throw new BaseException(ReissueExceptionEnum.INFO_NO_EXIST.getCode(), ReissueExceptionEnum.INFO_NO_EXIST.getMessage());
        }
        ReissueInfoResponse reissueInfoResponse = new ReissueInfoResponse();
        BeanUtils.copyProperties(reissue, reissueInfoResponse);
        //补发类型对照
        ReissueReasonEnum reissueReasonEnum = EnumUtil.getByCode(reissue.getReissueReason().intValue(), ReissueReasonEnum.class);
        if (reissueReasonEnum != null) {
            reissueInfoResponse.setReissueReasonStr(reissueReasonEnum.getDesc());
        }
        String supplierName = "";
        if (reissue.getSelfFlag() == SelfFlagEnum.SELF_FLAG_NO.getCode().byteValue()) {
            //根据供应商ID查询供应商名称 【仓储服务提供接口】
            ResponseResult<JmSupplierResponse> responseResult = supplyClient.findById(reissue.getSupplierId().longValue());
            Object object = responseResult.getData();
            if (object != null) {
                JmSupplierResponse jmSupplierResponse = JSON.parseObject(JSON.toJSONString(object), JmSupplierResponse.class);
                supplierName = jmSupplierResponse.getSupplierCompanyName();
            }
        } else {
            //根据实发仓ID查询实发仓名称 【仓储服务提供接口】
            supplierName = warehouseClient.findById(reissue.getSupplierId().longValue()).getData() != null ? warehouseClient.findById(reissue.getSupplierId().longValue()).getData().getWarehouseName() : "";
        }
        reissueInfoResponse.setBuyNum(reissue.getGoodsAmount());
        reissueInfoResponse.setActualNum(reissue.getRealSendAmount());
        reissueInfoResponse.setSupplierName(supplierName);
        return reissueInfoResponse;
    }

    /**
     * 补发原因--对照字典
     */
    public Map<Integer, String> getReissueReason() {
        Map<Integer, String> m = new HashMap<>();
        m.put(ReissueReasonEnum.REISSUE_MAKE_MISTAKES.getCode(), ReissueReasonEnum.REISSUE_MAKE_MISTAKES.getDesc());
        m.put(ReissueReasonEnum.REISSUE_SHIPMENT_REASON.getCode(), ReissueReasonEnum.REISSUE_SHIPMENT_REASON.getDesc());
        m.put(ReissueReasonEnum.REISSUE_EXPRESS_REASON.getCode(), ReissueReasonEnum.REISSUE_EXPRESS_REASON.getDesc());
        m.put(ReissueReasonEnum.REISSUE_PRODUCT_REASON.getCode(), ReissueReasonEnum.REISSUE_PRODUCT_REASON.getDesc());
        return m;
    }

    /**
     * 补发审核状态--对照字典
     */
    public Map<Integer, String> getReissueCheckStatus() {
        Map<Integer, String> m = new HashMap<>();
        m.put(ReissueCheckStatusEnum.CHECK_STATUS_WAIT.getCode(), ReissueCheckStatusEnum.CHECK_STATUS_WAIT.getDesc());
        m.put(ReissueCheckStatusEnum.CHECK_STATUS_PASSED.getCode(), ReissueCheckStatusEnum.CHECK_STATUS_PASSED.getDesc());
        m.put(ReissueCheckStatusEnum.CHECK_STATUS_FAILED.getCode(), ReissueCheckStatusEnum.CHECK_STATUS_FAILED.getDesc());
        return m;
    }


    /**
     * 补发状态--对照字典
     */
    public Map<Integer, String> getReissueStatus() {
        Map<Integer, String> m = new HashMap<>();
        m.put(ReissueStatusEnum.STATUS_WAIT.getCode(), ReissueStatusEnum.STATUS_WAIT.getDesc());
        m.put(ReissueStatusEnum.STATUS_PASSED.getCode(), ReissueStatusEnum.STATUS_PASSED.getDesc());
        m.put(ReissueStatusEnum.STATUS_FAILED.getCode(), ReissueStatusEnum.STATUS_FAILED.getDesc());
        m.put(ReissueStatusEnum.STATUS_CANCEL.getCode(), ReissueStatusEnum.STATUS_CANCEL.getDesc());
        return m;
    }

    /**
     * 补发类型--对照字典
     */
    public Map<Integer, String> getReissueType() {
        Map<Integer, String> m = new HashMap<>();
        m.put(ReissueTypeEnum.REISSUE_GOODS.getCode(), ReissueTypeEnum.REISSUE_GOODS.getDesc());
        m.put(ReissueTypeEnum.REISSUE_MISSED.getCode(), ReissueTypeEnum.REISSUE_MISSED.getDesc());
        m.put(ReissueTypeEnum.REISSUE_REPLACE.getCode(), ReissueTypeEnum.REISSUE_REPLACE.getDesc());
        return m;
    }

    /**
     * 生成订单号 补发
     */
    private String generateOrderSnBf() {
        String time = DateUtil.getAllMSTime().substring(2);
        int randomInt = ThreadLocalRandom.current().nextInt(10, 100);
        return "BF" + time + randomInt;
    }

    /**
     * 生成订单号 漏发
     */
    private String generateOrderSnLf() {
        String time = DateUtil.getAllMSTime().substring(2);
        int randomInt = ThreadLocalRandom.current().nextInt(10, 100);
        return "LF" + time + randomInt;
    }

    /**
     * 生成订单号 换货
     */
    private String generateOrderSnHh() {
        String time = DateUtil.getAllMSTime().substring(2);
        int randomInt = ThreadLocalRandom.current().nextInt(10, 100);
        return "HH" + time + randomInt;
    }

    /**
     * 生成订单号 售后订单号
     */
    private String generateOrderSnSh() {
        String time = DateUtil.getAllMSTime().substring(2);
        int randomInt = ThreadLocalRandom.current().nextInt(10, 100);
        return "SH" + time + randomInt;
    }
}
